const express = require('express');
const cors = require('cors');
const cookieParser = require('cookie-parser');
const path = require('path');

// 导入路由
const { router: authRoutes } = require('./routes/auth');
const trafficRoutes = require('./routes/traffic');
const thirdPartyRoutes = require('./routes/thirdParty');

// 导入数据库初始化
const { initDatabase } = require('./database/init');
const { trafficDetailQueries } = require('./database/queries');

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(cors({
  origin: 'http://localhost:5173', // Vue 开发服务器地址
  credentials: true
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());

// 静态文件服务
app.use(express.static(path.join(__dirname, '../frontend/dist')));

// API 路由
app.use('/flowapi/auth', authRoutes);
app.use('/flowapi/traffic', trafficRoutes);
app.use('/flowapi/third-party', thirdPartyRoutes);

// SPA 回退路由
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, '../frontend/dist/index.html'));
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ 
    success: false, 
    message: '服务器内部错误' 
  });
});

// 初始化数据库并启动服务器
async function startServer() {
  try {
    await initDatabase();
    console.log('数据库初始化完成');
    
    app.listen(PORT, () => {
      console.log(`服务器运行在 http://localhost:${PORT}`);
    });
  } catch (error) {
    console.error('启动服务器失败:', error);
    process.exit(1);
  }
}

startServer();
